<?php

namespace util\jwt;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
class Token
{
    private static $iss='$SJYf56UT8OBGNm2nE8Nj5mIs';//签发者：公司app_key
    private static $key='$2y$10$mVwFSJYx8iL4XnE8Nj5CSmILf5ZNjSl.BNc8KcUT8OBPVC1eTXGNm';
    public static function createToken($data = null)
    {
        $signer = new Sha256();//加密规则
        $time   = time();//当前时间

        $token = (new Builder())
            ->issuedBy(self::$iss)//签发人
            ->canOnlyBeUsedBy('student')//接收人
            ->identifiedBy('MarsLei', true) //标题id
            ->issuedAt($time)//发出令牌的时间
            ->canOnlyBeUsedAfter($time) //生效时间(即时生效)
            ->expiresAt($time + 3600) //过期时间
            ->with('data', $data) //用户数据
            ->sign($signer, self::$key) //签名
            ->getToken(); //得到token
        return (string)$token;
    }

    public static function verifyToken($token = null)
    {
        //检测是否接收到了token
        if (empty($token)) {
            return 0;
        }
        //转化为可以验证的token
        $token = (new Parser())->parse((string)$token);
        //验证基本设置
        $data = new ValidationData();
        $data->setIssuer(self::$iss);
        $data->setAudience('student');
        $data->setId('MarsLei');

        if (!$token->validate($data)) {
            return 0;
        }
        //验证签名
        $signer = new Sha256();
        if (!$token->verify($signer,  self::$key)) {
            return 0;
        }
        //验证通过，返回用户id数据
        return $token->getClaim('data');
    }
}